﻿#include "Glyph.h"

#include <freetype/freetype.h>
#include <freetype/ftglyph.h>
#include "Texture/Texture2D.h"
#include "Font/FontSubsystem.h"

SFreeTypeGlyph::~SFreeTypeGlyph()
{   
    if(Glyph)
    {
        FT_Done_Glyph((FT_Glyph)Glyph);
        Glyph=nullptr;
    }

}

TOptional<SCharTexture> SFreeTypeGlyph::LoadTexture()
{
    if(!bTextureLoaded)
    {
        bTextureLoaded=true;

        //从字形中获取位图
        FT_BitmapGlyph BitmapGlyph=(FT_BitmapGlyph)Glyph;
        FT_Bitmap& Bitmap=BitmapGlyph->bitmap;

        if(Bitmap.width==0 || Bitmap.rows==0)
        {
            //cant create texture,for example:  ' ' do not need render
            return TOptional<SCharTexture>();
        }

        auto Pool=RFontApplicationSubsystem::Get()->GetTextTexturePool();

        auto CharTexture=Pool->FindOrCreate(shared_from_this());
        Texture=CharTexture;

        //将位图写入字符纹理
        for(int32_t Line=0;Line<Bitmap.rows;Line++)
        {
            auto DataOffset=CharTexture.GetDataOffset(Line);
            memcpy(CharTexture.Texture->Data.Data()+ DataOffset
                ,Bitmap.buffer+Line*Bitmap.pitch,Bitmap.width);
        }
        CharTexture.Texture->SyncToRenderThread();

        // RTexture2D::STexture2DCreateInfo CreateInfo;
        // CreateInfo.ImageWidth=Bitmap.width;
        // CreateInfo.ImageHeight=Bitmap.rows;


        // CreateInfo.ImageFormat=ETextureFormat::R8;
        // CreateInfo.ImagePitch=Bitmap.pitch;
        // CreateInfo.RGBData=TVector<uint8_t>(Bitmap.buffer
        //     ,Bitmap.pitch*Bitmap.rows);

        // TSharedObjectPtr<RTexture2D> Result
        //     =RTexture2D::CreateFromCreateInfo(
        //     std::move(CreateInfo),(RObject*)Font.Get());

        // Texture=Result;
        // return Result;
    }

    return Texture;

}
